package org.example.realm;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.example.entity.User;
import org.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
@Slf4j
public class UsernameRealm extends AuthorizingRealm{

    private final UserMapper userMapper;

    @Autowired
    public UsernameRealm(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    /**
     * 认证
     * @param token
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        //获取用户名
        String username = token.getUsername();
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> eq = Wrappers.lambdaQuery(User.class).eq(User::getUsername, username);
        User user = userMapper.selectOne(eq);
        if(user!=null){
            if(user.getLockState()==1){
                throw new AuthenticationException("账号已被锁定，禁止登录");
            }
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), username);
        }else{
            throw new AuthenticationException("登录失败，用户名不存在！");
        }
    }

    /**
     * 授权
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        log.info("登录用户名:{}",name);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> permissions = new HashSet<>();
        permissions.add("user:delete");
        //permissions.add("user:update");
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }


}
